﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.Drawing;
using System.Drawing.Imaging;
using TiffUtil;


/*
 * A program to recursively convert TIF files to PDFs.
 * Error handling is not all that great, something to work on in the future.
 * Written on 18 June 2008 by Paul Schorfheide.
 */

namespace TiffBatch
{
    class Program
    {
        // Only takes one command line argument, the root directory for the conversion to start from.
        static void Main(string[] args)
        {
            //Check arguments and recurse.
            if (args.Length != 0)
                Convert(args[0]);
        }
        static void Convert(string directory)
        {
            string output = "";
            TiffUtil.TiffUtil myUtil = new TiffUtil.TiffUtil(@"C:\");
            //Recurse into child directories.
            try
            {
                foreach (string d in Directory.GetDirectories(directory))
                    Convert(d);
                foreach (string f in Directory.GetFiles(directory, "*.tif"))
                {
                    //Parse the file name to convert it to a .pdf extension.
                    for (int i = f.Length - 1; i >= 0; i--)
                    {
                        if (f[i] == '.')
                            output = f.Substring(0, i);
                    }
                    output += ".pdf";
                    //Create a new 8.5x11 PDF Document
                    Document pdfOut = new Document(PageSize.LETTER);
                    //Associate a system IO stream with the document.
                    PdfWriter.GetInstance(pdfOut, new FileStream(output, FileMode.Create));
                    //Open the document to insert data.
                    pdfOut.Open();
                    //Generate an image array consisting of all of the pages from the original tiff file.
                    System.Drawing.Image[] tiffPages = myUtil.splitTiffPages(System.Drawing.Image.FromFile(f));
                    foreach (System.Drawing.Image tiffPage in tiffPages)
                    {
                        //generate a pdf-compatible image from the array
                        iTextSharp.text.Image pdfPage = iTextSharp.text.Image.GetInstance(tiffPage, ImageFormat.Tiff);
                        //Scale the image to fit on a regular letter page
                        pdfPage.ScaleToFit(612, 792);
                        //Append the page to the pdf document.
                        pdfOut.Add(pdfPage);
                    }
                    //Closes the PDF document.
                    pdfOut.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }    
}